from google.appengine.ext import db
from datetime import date, datetime, timedelta
from horseanalysis.model.probability_sets.probability_result_base import ProbabilityResultBase
from horseanalysis.model.quinella_place import QuinellaPlace

class QuinellaPlaceProbabilityResult(ProbabilityResultBase):
  first_horse_no = db.IntegerProperty()
  second_horse_no = db.IntegerProperty()
  
  def update_gain_offset(self, results):
    if results.__contains__(str(self.first_horse_no)) and results.__contains__(str(self.second_horse_no)):
      self.gain_offset = self.odds
    else:
      self.gain_offset = 0.0
      
    self.put()
    
  @classmethod
  def cal_quinella_place_prob(cls, race_batch):
    winning_probability = cls.cal_win_prob(race_batch)
    available_horse_no = []
    qplace_prob_combination = {}

    for horse_no in winning_probability:
      available_horse_no.append(horse_no)

    for i in available_horse_no:
      for j in available_horse_no:
        for k in available_horse_no:
          if i != j and i != k and j != k:
            prob = cls.cal_individual_place_prob(winning_probability, i, j, k)
            keys = [i, j, k]
            keys.sort()
            
            for key in [str(keys[0])+'-'+str(keys[1]), str(keys[0])+'-'+str(keys[2]), str(keys[1])+'-'+str(keys[2])]:
              if not qplace_prob_combination.has_key(key):
                qplace_prob_combination[key] = 0
              qplace_prob_combination[key] += prob

    return qplace_prob_combination
  
  @classmethod
  def __analyze_batch__(cls, race_batch):
    probability = cls.cal_quinella_place_prob(race_batch)
    odds = QuinellaPlace.get_hashed_odds(race_batch)
    
    for horse_combination in probability:
      horse_nos = horse_combination.split('-')
      cls.create_new_result(race_batch, int(horse_nos[0]), int(horse_nos[1]), odds[horse_combination], probability[horse_combination], odds[horse_combination] * probability[horse_combination])
  
  @classmethod
  def create_new_result(cls, race_batch, first_horse_no, second_horse_no, odds, probability, expected_return):
    scheme = cls(race_batch=race_batch, odds=odds, first_horse_no=first_horse_no, second_horse_no=second_horse_no, probability=probability, expected_return=expected_return)
    scheme.put()
  
  @classmethod
  def complete_related_race_batch_probability_result(cls, race_batch):
    race_batch.set_completed_quinella_place_probability_set(True)
  
  @classmethod
  def incomplete_related_race_batch_probability_result(cls, race_batch):
    race_batch.set_completed_quinella_place_probability_set(False)
  